package org.looop.studio.noots.index;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.looop.studio.noots.BaseTestCase;
import org.looop.studio.noots.util.FileUtil;

public abstract class BaseIndexingTestCase extends BaseTestCase {
	protected String[] keywords = {"1", "2"};
	protected String[] unindexed = {"Netherlands", "Italy"};
	protected String[] unstored = {"Amsterdam has lots of bridges", "Venice has lots of canals"};
	protected String[] text = {"Amsterdam", "Venice"};
	protected Directory dir;
	protected void setUp() throws Exception {
		String indexDir = getIndexDir();
		dir = FSDirectory.getDirectory(indexDir, true);
		addDocuments(dir);
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		File file = new File(getIndexDir());
		FileUtil.deleteFile(file);
	}
	
	protected void addDocuments(Directory dir) throws IOException {
		IndexWriter writer = new IndexWriter(dir, getAnalyzer(), true);
		writer.setUseCompoundFile(isCompund());
		for(int i=0; i < keywords.length; i++){
			Document doc = new Document();
			doc.add(Field.Keyword("id", keywords[i]));
			doc.add(Field.UnIndexed("country", unindexed[i]));
			doc.add(Field.UnStored("contents", unstored[i]));
			doc.add(Field.Text("city", text[i]));
			writer.addDocument(doc);
		}
		writer.optimize();
		writer.close();
	}
	
	protected int getHitCount(String fieldName, String searchString) throws IOException {
		IndexSearcher searcher = new IndexSearcher(dir);
		Term t = new Term(fieldName, searchString);
		Query query = new TermQuery(t);
		Hits hits = searcher.search(query);
		int hitCount = hits.length();
		searcher.close();
		return hitCount;
	}
	
	public static void main(String[] args) {
		Random rand = new Random(new Date().getTime());
		Map<Integer, Integer> count = new HashMap<Integer, Integer>();
		for(int i=0; i < 10000; i++){
			int value = Math.abs(rand.nextInt()) % 3;
			increase(count, value);
		}
		System.out.println(count);
	}
	
	public static void increase(Map<Integer, Integer> map, Integer value){
		if(map.get(value) == null){
			map.put(value, 1);
		}else{
			map.put(value, map.get(value)+1);
		}
	}
	
}
